
#include <thread>
#include <unistd.h>
#include <atomic>
#include <cstdio>
#include <functional>

#include "siteService/nlohmann/json.hpp"
#include "siteService/service_site_manager.h"
#include "qlibc/FileUtils.h"
#include "param.h"
#include "common/httpUtil.h"
#include "service/service.h"
#include "service/serviceRequestHandler.h"
#include "sourceManage/deviceManager.h"
#include "sourceManage/groupManager.h"
#include "sourceManage/statusManager.h"
#include "log/Logging.h"

using namespace std;
using namespace servicesite;
using namespace httplib;
using namespace std::placeholders;
using json = nlohmann::json;

int main(int argc, char* argv[]) {
    //增加log打印
    string path = "/data/changhong/edge_midware/lhy/synergySiteLog.txt";
    muduo::logInitLogger(path);

    LOG_RED << "-----------------------------------------";
    LOG_RED << "-----------------------------------------";
    LOG_RED << "---------------SYNERGY START-------------";
    LOG_RED << "-----------------------------------------";
    LOG_RED << "-----------------------------------------";

    httplib::ThreadPool threadPool_(10);

    // 创建 serviceSiteManager 对象, 单例
    ServiceSiteManager* serviceSiteManager = ServiceSiteManager::getInstance();
    serviceSiteManager->setServerPort(SynergySitePort);
    serviceSiteManager->setSiteIdSummary(SynergySiteID, SynergySiteName);

    //单例对象
    DeviceManager::getInstance();   
    GroupManager::getInstance();
    StatusManager::getInstance();
    siteManager::getInstance();


//注册服务
        
    //注册设备控制回调
    serviceSiteManager->registerServiceRequestHandler(Control_Device_Service_ID,
                                                      [](const Request& request, Response& response) -> int{
        return synergy::deviceControl_service_handler(request, response);
    });



    //获取设备列表
    serviceSiteManager->registerServiceRequestHandler(Get_DeviceList_Service_ID,
                                                      [](const Request& request, Response& response) -> int{
        return synergy::getDeviceList_service_handler(request, response);
    });


    //获取所有设备状态
    serviceSiteManager->registerServiceRequestHandler(Get_DeviceState_All_Service_ID,
                                                      [](const Request& request, Response& response) -> int{
        return synergy::get_device_state_all_service_handler(request, response);
    });


    //控制分组
    serviceSiteManager->registerServiceRequestHandler(ControlGroup_Device_Service_ID,
                                                      [](const Request& request, Response& response) -> int{
        return synergy::groupControl_service_handler(request, response);
    });

    //获取分组列表
    serviceSiteManager->registerServiceRequestHandler(GetGroupList_Device_Service_ID, synergy::getGroupList_service_handler);

    //请求设备列表更新
    serviceSiteManager->registerServiceRequestHandler(UpdateDeviceList_Service_ID,
                                                      [](const Request& request, Response& response)->int{
        return synergy::updateDeviceList_service_handler(request, response);
    });

    //请求组列表更新
    serviceSiteManager->registerServiceRequestHandler(UpdateGroupList_Service_ID,
                                                      [](const Request& request, Response& response)->int{
        return synergy::updateGroupList_service_handler(request, response);
    });



    //发布消息
    serviceSiteManager->registerServiceRequestHandler(MessagePublish_Service_ID,
                                                      [](const Request& request, Response& response) -> int{
        return synergy::messagePublish_service_request_handler(request, response);
    });

    
    //声明消息
    //转发的蓝牙站点消息声明
   
    serviceSiteManager->registerMessageId(Device_State_Changed);           //设备状态改变
    serviceSiteManager->registerMessageId(DeviceListChanged);              //设备列表变更

    //转发的zigbee站点消息声明
    serviceSiteManager->registerMessageId(DeviceOnOffLineMsg);             //设备上下线
    serviceSiteManager->registerMessageId(TriggerSceneMsg);                //场景触发消息
    serviceSiteManager->registerMessageId(Device_State_Notify);            //场景触发消息
    serviceSiteManager->registerMessageId(Device_Online_Notify);           //场景触发消息

    //bt_device站点消息声明
    serviceSiteManager->registerMessageId(KeyValue_MessageID);              //场景触发消息

   
    
    //本站点产生的消息
    serviceSiteManager->registerMessageId(Scene_Msg_MessageID);             //场景指令消息
    serviceSiteManager->registerMessageId(Mms_messageID);                   //消息回显服务
    serviceSiteManager->registerMessageId(ReportTTS_messageID);             //语音播报消息


    //注册消息处理函数
    serviceSiteManager->registerMessageHandler(Device_State_Changed,          "ble_light", synergy::messagePublish);        //设备状态改变
    serviceSiteManager->registerMessageHandler(DeviceListChanged,             "ble_light", synergy::messagePublish);        //设备列表变更

    serviceSiteManager->registerMessageHandler(DeviceOnOffLineMsg,            "zigbee_light", synergy::messagePublish);     //设备上下线
    serviceSiteManager->registerMessageHandler(SingleDeviceBindSuccessMsg,    "zigbee_light", synergy::messagePublish);     //单设备绑定
    serviceSiteManager->registerMessageHandler(TriggerSceneMsg,               "zigbee_light", synergy::messagePublish);     //场景触发
    serviceSiteManager->registerMessageHandler(Device_State_Notify,           "zigbee_light", synergy::messagePublish);     //设备状态改变
    serviceSiteManager->registerMessageHandler(Device_Online_Notify,          "zigbee_light", synergy::messagePublish);     //设备上下线消息
    serviceSiteManager->registerMessageHandler(Key_bind_success_messageID,    "zigbee_light", synergy::messagePublish);     //红外设备绑定成功

   


    serviceSiteManager->registerMessageHandler(AllUpdate_MessageID,           "master_coordinate", synergy::trigger_dgp_update_meesageHandle);  //触发设备、在线面板更新
    serviceSiteManager->registerMessageHandler(Site_OnOffLine_MessageID,       "site_query", synergy::trigger_devGrp_update_messageHandle); //触发设备类站点更新
    


    // 订阅主从站点消息
    threadPool_.enqueue([&](){
        subscribe_master_message();
    });

    // 订阅查询站点消息
    threadPool_.enqueue([&](){
        subscribe_query_message();
    });


    // 站点监听线程启动
    threadPool_.enqueue([&](){
        while(true){
            //自启动方式
            // int code = serviceSiteManager->start();
            //注册启动方式
            int code = serviceSiteManager->startByRegister();
            if(code != 0){
                std::cout << "===>synergySite startByRegister error, code = " << code << std::endl;
                std::cout << "===>synergySite startByRegister in 3 seconds...." << std::endl;
                std::this_thread::sleep_for(std::chrono::seconds(3));
            }else{
                std::cout << "===>synergySite startByRegister successfully....." << std::endl;
                break;
            }
        }
    });

    while(true){
        std::this_thread::sleep_for(std::chrono::seconds(60 *10));
    }

    return 0;
}
